/**
 *
 * Copyright (C) 2008  Igor Vdovichenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * Though a sincere effort has been made to deliver a professional,
 * quality product,the library itself is distributed WITHOUT ANY WARRANTY;
 * See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 */
package com.vin.scriptutils.utils.ssh.trilead;

import com.trilead.ssh2.Connection;
import com.vin.scriptutils.utils.ssh.ConnectionInfo;
import com.vin.scriptutils.utils.ssh.SshConnection;
import java.io.IOException;

/**
 *
 * @author igor
 */
public class TrileadSshConnection extends SshConnection {

    private Connection connection;
    private long waitForConditionTimeout = 1000;
    private int keyExchangeTimeout = 0;

    public TrileadSshConnection() {
        super();
    }

    public TrileadSshConnection(final ConnectionInfo ci) {
        super(ci);
    }

    synchronized Connection setConnection() {
        if (this.connection == null) {
            this.connection = new Connection(getHostAddress(), getPort());
        }
        return this.connection;
    }

    public synchronized Connection getConnection() {
        return this.connection;
    }

    public int getKeyExchangeTimeout() {
        return keyExchangeTimeout;
    }

    public long getWaitForConditionTimeout() {
        return waitForConditionTimeout;
    }

    public void setKeyExchangeTimeout(int keyExchangeTimeout) {
        this.keyExchangeTimeout = keyExchangeTimeout;
    }

    public void setWaitForConditionTimeout(long waitForConditionTimeout) {
        this.waitForConditionTimeout = waitForConditionTimeout;
    }

    public TrileadSshConnection WaitForConditionTimeout(long waitForConditionTimeout) {
        setWaitForConditionTimeout(waitForConditionTimeout);
        return this;
    }

    public TrileadSshConnection KeyExchangeTimeout(int keyExchangeTimeout) {
        setKeyExchangeTimeout(keyExchangeTimeout);
        return this;
    }

    @Override
    public synchronized boolean authenticate() throws IOException {
        if (getPassword() != null && getPassword().length() > 0) {
            return getConnection().authenticateWithPassword(getUsername(), getPassword());
        } else {
            return getConnection().authenticateWithNone(getUsername());
        }
    }
}
